﻿using IRepository;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Dapper;
using ModelCache;

namespace Repository
{
    public class BaseRepository_1<T> : IBaseRepository<T> where T : class
    {
        protected DbConnection GetDbConnection(string constr)
        {
            var con = new MySql.Data.MySqlClient.MySqlConnection(constr);
            con.Open();
            return con;
        }

        public int Add(T t, string constr)
        {
            using (var con = GetDbConnection(constr))
            {
                return con.Execute(ModelCache<T>._AddSql, t);
            }
        }

        public IQueryable<T> Find(Expression<Func<T, bool>> expression, string constr, bool isUpdate = false)
        {
            throw new NotImplementedException();
        }

        public int Remove(T t, string constr)
        {
            using (var con = GetDbConnection(constr))
            {
                return con.Execute(ModelCache<T>._DeleteSql, t);
            }
        }

        public int Update(T t, string constr)
        {
            using (var con = GetDbConnection(constr))
            {
                return con.Execute(ModelCache<T>._UpdateSql, t);
            }
        }

        public T Find(int id, string constr)
        {
            using (var con = GetDbConnection(constr))
            {
                Dapper.DynamicParameters dynamicParameters = new DynamicParameters();
                dynamicParameters.Add(ModelCache<T>._PrimaryKey, id);
                return con.Query<T>(ModelCache<T>._FindSql, dynamicParameters).FirstOrDefault();
            }
        }
        public IEnumerable<T> GetAll(string constr)
        {
            using (var con = GetDbConnection(constr))
            {
                return con.Query<T>(ModelCache<T>._GetAllSql);
            }
        }
    }
}
